package com.wmvc01;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(value = Exception.class)
  public void resolveException(HttpServletRequest request, HttpServletResponse response,
      Exception ex) {
    try {
      Map<String, Object> map = new HashMap<>();
      map.put("code", "500");
      map.put("info", "internal exception");
      map.put("data", "");
      ObjectMapper objectMapper = new ObjectMapper();
      response.setContentType("application/json; charset=utf-8");
      response.getWriter().write(objectMapper.writeValueAsString(map));
    } catch (Exception e) {
      System.out.println(">> write exception info to client failed");
    }
  }
}
